<?php
/**
 * Description of Class_Forum
 *
 * @author Fantastik78
 */

class Forum {

    //ERRORS
        //createTopic
        private $e_title = false;
        private $e_content = false;
        //writePost
        private $e_title_post = false;


    // Allows to know if the post's date is today
    private function todayDate($dateDB){
        if(date("d F o") == date("d F o",$dateDB)){
            $date = "Aujourd'hui, " . date("G\hi",$dateDB);
        }else{
            $date = date("d F o, G\hi",$dateDB);
        }
        return $date;
    }

    // Get the Errors CreateTopic
    public function getErrorsCreateTopic(){
        if(isset($_POST['create_topic'])){
            if($this->e_title){ echo "Le topic doit posseder un titre.<br/>";}
            if($this->e_content){ echo "Le topic doit posseder un contenu.<br/>";}
            echo "<br/>";
        }
    }

    // Create a Thread
    public function createThread($pseudo){
        if(isset($_POST['create_topic'])){
            $post_secu = array_map("mysql_real_escape_string", $_POST);
            if(trim($post_secu['title_topic']) != null){
                if(trim($post_secu['content_topic']) != null){
                    if($_SESSION['member_session']['team'] != null && $_SESSION['member_session']['id'] != null){
                        mysql_query("INSERT INTO forum (subject, content, creator, date, team_id) VALUES ('" . $post_secu['title_topic'] . "', '" . $post_secu['content_topic'] . "', '" . $pseudo . "', '" . time() . "', '" . $_SESSION['member_session']['team'] . "')");
                        }
                }else{
                    $this->e_content = true;
                }
            }else{
                $this->e_title = true;
            }
        }
    }

    // Get all Thread from a special team ID
    public function getForum(){
        $query = mysql_query("SELECT * FROM forum WHERE team_id='" . $_SESSION['member_session']['team'] . "'");
        $i = 0;
        while ($row = mysql_fetch_array($query)) {
            if($i&1){
                $class_parity = "line_impair";
            }else{
                $class_parity = "line_pair";
            }
            echo "<tr class=\"" . $class_parity . "\"><td></td>";
            echo "<td><a href=".ROOT."/topic?topic=" . $row['id'] . ">" . htmlentities($row['subject']) . "</a></td>";
            echo "<td>" . htmlentities($row['creator']) . "</td>";
            echo "<td>" . htmlentities(date("\l\e d F o", $row['date'])) . "</td>";
            echo "<td>null</td></tr>";
            $i++;
        }
    }


    // Write a post in the current Thread
    public function writePost($pseudo){
        if(isset($_POST['write_post'])){
            $post_secu = array_map("mysql_real_escape_string", $_POST);
            if(trim($post_secu['content']) != null){
                if(!isset($_GET['edit'])){
                    $queryIns = mysql_query("INSERT INTO message ( content, date, creator, topic_id) VALUES ('" . $post_secu['content'] . "','" . time() . "','" . $pseudo . "','" . $_GET['topic'] . "')");
                }else{
                    $queryUpd = mysql_query("UPDATE message SET content='" .$post_secu['content']. "' WHERE id='" . $_GET['edit'] . "'");
                    header("Location:" . $_SERVER['PHP_SELF'] . "?topic=" . $_GET['topic']);
                    exit();
                }
            }else{
                $this->e_title_post = true;
            }
        }
    }

    public function getTitleThread(){
        $query = mysql_query("SELECT subject FROM forum WHERE id='" . $_GET['topic'] . "'");
        $res = mysql_fetch_array($query);
        return $res;
        }

    // Recover the first post that was created when creating the topic
    public function getThreadFirstTopic($pseudo){
        if(isset($_GET['topic']) AND !isset($_GET['p'])){
           $query = mysql_query("SELECT * FROM forum WHERE id='" . $_GET['topic'] . "'");
           while ($row = mysql_fetch_array($query)) {

                $date = $this->todayDate($row['date']);

               echo "<tr><td class=\"td_header_left\">" . $date . "</td><td class=\"td_header_right\"></td></tr>";
               echo "<tr class=\"space_table\"><td></td><td></td>";
               echo "<tr><td class=\"td_middle\"><span class=\"creator\">" . htmlspecialchars($row['creator']) . "</span></td><td class=\"td_middle\">" . nl2br(htmlspecialchars($row['content'])) . "</td></tr>";
               echo "<tr><td class=\"td_MP\">";
               if($row['creator'] != $pseudo){ echo "<a href=\"message.php?sendto=" . $row['creator'] . "\"><img src=\"../ressources/images/mp.png\" /></a>";}
               echo "</td><td class=\"td_modify\">";
               if($row['creator'] == $pseudo){
                   echo '<a href="' . $_SERVER['REQUEST_URI'] .'&amp;delete=' . $row['id'].
                   '"><img src="../ressources/images/delete.png" alt="delete"/></a><a href="' .$_SERVER['REQUEST_URI'] . '&amp;edit=' . $row['id'] . '"><img src="../ressources/images/write.png" alt="modify"/></a>';
               }
               echo "</td></tr>";
               echo "<tr class=\"space_table2\"><td></td><td></td>";
           }
        }
    }

    private function pagination(){
        $limit = array();
        if(isset($_GET['p'])){
            $limit['debut'] = $_GET['p']-1;
            $limit['nombre'] = 5;
        }else{
            $limit['debut'] = 0;
            $limit['nombre'] = 4;
        }
        return $limit;
    }
    
    public function pageNumber(){
        if(isset($_GET['topic'])){
            $pages = array();
            $query = mysql_query("SELECT COUNT(*) as nb FROM message WHERE topic_id='".$_GET['topic']."'");
            $res = mysql_fetch_array($query);
            $pages['number'] = ceil($res['nb']/5);
            $pages['current'] = 0;
            if(isset($_GET['p'])){
                $pages['current']  = $_GET['p']/5+1;
            }else{
                $pages['current'] = 1;
            }
            return $pages;
        }
        
    }
    
    // Get all post from the current topic
    public function getAllPost($pseudo){
        if(isset($_GET['topic'])){
            $limit = $this->pagination();
            $query = mysql_query("SELECT * FROM message WHERE topic_id='" . $_GET['topic'] . "' ORDER BY date LIMIT ".$limit['debut'].", ".$limit['nombre']);
            while ($row = mysql_fetch_array($query)) {

                $date = $this->todayDate($row['date']);
                
               echo "<tr><td class=\"td_header_left\">" . $date . "</td><td class=\"td_header_right\"></td></tr>";
               echo "<tr class=\"space_table\"><td></td><td></td>";
               echo "<tr><td class=\"td_middle\"><span class=\"creator\">" . htmlspecialchars($row['creator']) . "</span></td><td class=\"td_middle content\">" . nl2br(htmlspecialchars($row['content'])) . "</td></tr>";
               echo "<tr><td class=\"td_MP\">";
               if($row['creator'] != $pseudo){ echo "<a href=\"message.php?sendto=" . $row['creator'] . "\"><img src=\"../ressources/images/mp.png\" /></a>";}
               echo "</td><td class=\"td_modify\">";
               if($row['creator'] == $pseudo){
                   echo '<a href="' . $_SERVER['REQUEST_URI'] .'&amp;delete=' . $row['id'].
                   '"><img src="../ressources/images/delete.png" alt="delete"/></a><a href="' .$_SERVER['REQUEST_URI'] . '&amp;edit=' . $row['id'] . '#post_message"><img src="../ressources/images/write.png" alt="modify"/></a>';
               }
               echo "</td></tr>";
               echo "<tr class=\"space_table2\"><td></td><td></td>";
            }
        }
    }

    public function deletePost(){
        if(isset($_GET['delete'])){
            $query = mysql_query("DELETE FROM message WHERE id='" . $_GET['delete'] . "'");
            $param = explode("&", $_SERVER['QUERY_STRING']);
            header("Location:" . $_SERVER['PHP_SELF'] ."?". $param[0]);
            exit();
        }
    }

    public function editPost(){
        if(isset($_GET['edit'])){
            $query = mysql_query("SELECT * FROM message WHERE id='" . $_GET['edit'] . "'");
            $nb_row = mysql_num_rows($query);
            if($nb_row != 0){
                $array_result = mysql_fetch_array($query);
                return $array_result;
            }
            return null;
        }
    }
    
    public function lastMessage(){
        
        $query = mysql_query("SELECT id FROM forum");
        $list_message = array();
        $i = 0;
        
        while($list_topic = mysql_fetch_assoc($query))
        {
            $query2 = mysql_query("SELECT m.*, f.subject FROM forum f JOIN message m WHERE f.id='".$list_topic['id']."' AND f.id = m.id AND f.team_id ='".$_SESSION['member_session']['team']."' ORDER BY m.date LIMIT 0, 1");
            $list_message[$i] = mysql_fetch_assoc($query2);
            $i++;
        }
        
        $i = 0;
        foreach($list_message as $msg)
        {
            if($i>4)
                break;
            echo '<tr><td>'.$msg['subject'].'</td>';
            echo '<td>'.$msg['creator'].'</td>';
            echo '<td>'.$this->todayDate($msg['date']).'</td></tr>';
            $i++;
        }
        
        
    }

}

?>
